package com.bw.common.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.jwt.JWT;
import com.bw.common.domain.SysMenu;
import com.bw.common.service.SysMenuService;
import com.bw.common.units.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @RequestMapping("/list")
    public Result list(){
        //解析token，获取登录用户
        String token = request.getHeader("token");
        JWT of = JWT.of(token);
        Integer id = (Integer) of.getPayload("id");
        List<Integer> ids=new LinkedList<>();
        List<SysMenu> menuList = sysMenuService.listbyuserid(id);
        for (SysMenu sysMenu : menuList) {
            if (sysMenu.getParentId()!=null){
                if (!ids.contains(sysMenu.getParentId())){
                    ids.add(sysMenu.getParentId());
                }
            }
        }
//       获取
        for (Integer integer : ids) {
            SysMenu menu = sysMenuService.getById(integer);
            if (!menuList.contains(menu) && menu!=null){
                menuList.add(menu);
            }
        }
        System.err.println(menuList);
        //转为树形结构
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
//转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.<SysMenu, String>build(menuList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId()+"");
                    tree.setParentId(treeNode.getParentId()+"");
                    tree.setName(treeNode.getName()+"");
                    // 扩展属性 ...
                    tree.putExtra("path", treeNode.getPath());
                    tree.putExtra("component", treeNode.getComponent());
                });
        return Result.success(treeNodes);
    }

}
